<template>
  <div class="pui-input-number pui-input" :class="[size, full && 'full-fill']" :style="{ width: width }">
    <input
      class="pui-input_frame"
      type="number"
      v-model="componetnValue"
      :placeholder="placeholder"
      :disabled="disabled"
      :readonly="readonly"
      :step="props.step"
    />
    <slot></slot>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'pui-input-number',
});
</script>

<script lang="ts" setup>
import { ref, watch } from 'vue';

import { Props } from './interface';

const props = withDefaults(defineProps<Props>(), {
  min: Number.MIN_VALUE,
  max: Number.MAX_VALUE,
  modelValue: 0,
});

const emits = defineEmits<{
  'update:modelValue': [vale: number | string];
}>();

const formattedValue = (num: string) => {
  if (num === '') {
    return '';
  }
  let value = Number(num);
  if (isNaN(value)) {
    return '';
  }
  if (value < props.min) {
    value = props.min;
  }
  if (value > props.max) {
    value = props.max;
  }
  if (props.precision !== undefined) {
    return value.toFixed(props.precision);
  }
  return value.toString();
};
const componetnValue = ref(formattedValue(props.modelValue.toString()));

watch(
  () => componetnValue.value,
  (newVal) => {
    if (newVal) {
      const val = formattedValue(newVal);
      emits('update:modelValue', val);
      componetnValue.value = val;
    }
  }
);
</script>
